Imports System
Imports System.Collections
Imports System.Collections.Generic
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports com.amazon.webservices


Namespace sk.BLL
    <Serializable()> _
    Public Class ShoppingCartItem
        Private _id As Integer = 0
        Public Property ID() As Integer
            Get
                Return _id
            End Get
            Private Set(ByVal value As Integer)
                _id = value
            End Set
        End Property

        Private _title As String = ""
        Public Property Title() As String
            Get
                Return _title
            End Get
            Private Set(ByVal value As String)
                _title = value
            End Set
        End Property

        Private _ASIN As String = ""
        Public Property ASIN() As String
            Get
                Return _ASIN
            End Get
            Private Set(ByVal value As String)
                _ASIN = value
            End Set
        End Property

        Private _unitPrice As Decimal
        Public Property UnitPrice() As Decimal
            Get
                Return _unitPrice
            End Get
            Private Set(ByVal value As Decimal)
                _unitPrice = value
            End Set
        End Property

        Private _quantity As Integer = 1
        Public Property Quantity() As Integer
            Get
                Return _quantity
            End Get
            Set(ByVal value As Integer)
                _quantity = value
            End Set
        End Property

        Public Sub New(ByVal ASIN As String, ByVal product As ProductObj)
            'Me.ID = id
            Me.Title = product.Title
            Me.ASIN = ASIN
            Me.UnitPrice = product.Price
        End Sub
    End Class



    <Serializable()> _
    Public Class ShoppingCart

        ' This are used by Amazon Web Services
        Private _AmazonCartID As String
        Private _AmazonHMAC As String
        Private _AmazonURLEncodedHMAC As String
        Private _AmazonPurchaseURL As String

        Private Sub CreateCart(ByVal ASIN As String)
            Dim service As New AWSECommerceService()

            Dim cartCreate As New CartCreate()

            Dim request As New CartCreateRequest()

            cartCreate.SubscriptionId = "0525E2PQ81DD7ZTWTK82"
            cartCreate.AssociateTag = "signkids-20"

            request.ResponseGroup = New String() {"Cart"}

            Dim items(0) As CartCreateRequestItem

            items(0) = New CartCreateRequestItem
            items(0).ASIN = ASIN
            items(0).Quantity = "1"

            request.Items = items

            ' Setup request
            cartCreate.Request = New CartCreateRequest() {request}

            ' Get the response
            Dim response As CartCreateResponse
            response = service.CartCreate(cartCreate)

            If response Is Nothing Then
                Throw New Exception("Server Error - no response recieved!")
            End If

            Dim cartArray As Cart() = response.Cart()

            ' Check for errors, stop at first error
            If cartArray Is Nothing Then
                Throw New Exception("Server Error - empty response!")
            End If

            If cartArray(0).Request.Errors IsNot Nothing Then
                Throw New Exception(cartArray(0).Request.Errors(0).Message)
            End If

            For Each cart As Cart In cartArray

                If cart IsNot Nothing Then
                    _AmazonCartID = cart.CartId
                    _AmazonHMAC = cart.HMAC
                    _AmazonURLEncodedHMAC = cart.URLEncodedHMAC
                    _AmazonPurchaseURL = cart.PurchaseURL

                    Dim subTotalCart As Price = cart.SubTotal
                    If subTotalCart IsNot Nothing Then
                        'Console.WriteLine("FormattedPrice: {0}", subTotalCart.FormattedPrice)
                    End If
                End If

            Next
        End Sub




        Private _items As New Dictionary(Of String, ShoppingCartItem)()
        Public ReadOnly Property Items() As ICollection
            Get
                Return _items.Values
            End Get
        End Property

        Public ReadOnly Property PurchaseURL() As String
            Get
                Return _AmazonPurchaseURL
            End Get
        End Property

        ''' <summary>
        ''' Gets the sum total of the items' prices
        ''' </summary>
        Public ReadOnly Property Total() As Decimal
            Get
                Dim sum As Decimal = 0D
                For Each item As ShoppingCartItem In _items.Values
                    sum += item.UnitPrice * item.Quantity
                Next
                Return sum
            End Get
        End Property

        ''' <summary>
        ''' Adds a new item to the shopping cart
        ''' </summary>
        Public Sub InsertItem(ByVal ASIN As String, ByVal Product As ProductObj)

            If _items.ContainsKey(ASIN) Then
                _items(ASIN).Quantity += 1
                ' call code to modify Amazon cart
            Else
                _items.Add(ASIN, New ShoppingCartItem(ASIN, Product))

                If _AmazonHMAC Is Nothing Then
                    CreateCart(ASIN)
                Else
                    addItems(ASIN)
                End If

            End If
        End Sub

        Private Sub addItems(ByVal ASIN As String)
            Dim service As New AWSECommerceService()
            Dim cartAdd As New CartAdd()
            Dim request As New CartAddRequest()

            CartAdd.SubscriptionId = "0525E2PQ81DD7ZTWTK82"
            CartAdd.AssociateTag = "signkids-20"

            Request.ResponseGroup = New String() {"Cart"}
            request.CartId = _AmazonCartID
            request.HMAC = _AmazonHMAC

            Dim items(0) As CartAddRequestItem

            items(0) = New CartAddRequestItem
            items(0).ASIN = ASIN
            items(0).Quantity = "1"

            request.Items = items

            ' Setup request
            CartAdd.Request = New CartAddRequest() {Request}

            ' Get the response
            Dim response As CartAddResponse = service.CartAdd(CartAdd)
            If response Is Nothing Then
                Throw New Exception("Server Error - no response recieved!")
            End If

            Dim cartAddArray As Cart() = response.Cart

            ' Check for errors, stop at first error
            If cartAddArray Is Nothing Then
                Throw New Exception("Server Error - empty response!")
            End If

            If cartAddArray(0).Request.Errors IsNot Nothing Then
                Throw New Exception(cartAddArray(0).Request.Errors(0).Message)
            End If

            ' ================== RESPONSE GROUP Cart =================
            For Each cart As Cart In cartAddArray

                If cart IsNot Nothing Then

                    Dim subTotalCart As Price = cart.SubTotal

                    If subTotalCart IsNot Nothing Then
                        'Console.WriteLine(" === SubTotal === ")
                        'Console.WriteLine("Amount: {0}", subTotalCart.Amount)
                        'Console.WriteLine("CurrencyCode: {0}", subTotalCart.CurrencyCode)
                        'Console.WriteLine("FormattedPrice: {0}", subTotalCart.FormattedPrice)
                    End If
                End If
            Next
        End Sub

        ''' <summary>
        ''' Removes an item from the shopping cart
        ''' </summary>
        Public Sub DeleteItem(ByVal ASIN As String)
            If _items.ContainsKey(ASIN) Then
                Dim item As ShoppingCartItem = _items(ASIN)
                item.Quantity -= 1
                If item.Quantity = 0 Then
                    _items.Remove(ASIN)
                End If
            End If
        End Sub

        ''' <summary>
        ''' Removes all items of a specified product from the shopping cart
        ''' </summary>
        Public Sub DeleteProduct(ByVal ASIN As String)
            If _items.ContainsKey(ASIN) Then
                _items.Remove(ASIN)
            End If
        End Sub

        ''' <summary>
        ''' Updates the quantity for an item
        ''' </summary>
        Public Sub UpdateItemQuantity(ByVal ASIN As String, ByVal quantity As Integer)
            If _items.ContainsKey(ASIN) Then
                Dim item As ShoppingCartItem = _items(ASIN)
                item.Quantity = quantity
                If item.Quantity <= 0 Then
                    _items.Remove(ASIN)
                End If
            End If
        End Sub

        ''' <summary>
        ''' Clears the cart
        ''' </summary>
        Public Sub Clear()
            _items.Clear()

            Dim service As New AWSECommerceService()
            Dim cartClear As New CartClear()
            Dim request As New CartClearRequest()

            cartClear.SubscriptionId = "0525E2PQ81DD7ZTWTK82"
            cartClear.AssociateTag = "signkids-20"

            request.ResponseGroup = New String() {"Cart"}
            request.CartId = _AmazonCartID
            request.HMAC = _AmazonHMAC

            ' Setup request
            cartClear.Request = New CartClearRequest() {request}

            ' Get the response
            Dim response As CartClearResponse = service.CartClear(cartClear)
            If response Is Nothing Then
                Throw New Exception("Server Error - no response recieved!")
            End If

            Dim cartClearArray As Cart() = response.Cart()

            ' Check for errors, stop at first error
            If cartClearArray Is Nothing Then
                Throw New Exception("Server Error - empty response!")
            End If

            If cartClearArray(0).Request.Errors IsNot Nothing Then
                Throw New Exception(cartClearArray(0).Request.Errors(0).Message)
            End If

            _AmazonCartID = Nothing
            _AmazonHMAC = Nothing
            _AmazonURLEncodedHMAC = Nothing
            _AmazonPurchaseURL = Nothing

        End Sub
    End Class

    Public Class CurrentUserShoppingCart
        Public Shared Function GetItems() As ICollection
            Return TryCast(HttpContext.Current.Profile, ProfileCommon).ShoppingCart.Items
        End Function

        Public Shared Sub DeleteItem(ByVal ASIN As String)
            TryCast(HttpContext.Current.Profile, ProfileCommon).ShoppingCart.DeleteItem(ASIN)
        End Sub

        Public Shared Sub DeleteProduct(ByVal ASIN As Integer)
            TryCast(HttpContext.Current.Profile, ProfileCommon).ShoppingCart.DeleteProduct(ASIN)
        End Sub
    End Class
End Namespace